# Copyright (c) 2021 Juan Miguel Jimeno
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, GroupAction, IncludeLaunchDescription
from launch.substitutions import LaunchConfiguration, Command, PathJoinSubstitution, EnvironmentVariable, TextSubstitution
from launch.conditions import IfCondition
from launch_ros.actions import Node, PushRosNamespace
from launch_ros.substitutions import FindPackageShare
from launch.launch_description_sources import PythonLaunchDescriptionSource

def generate_launch_description():
    robot_base = os.getenv('LINOROBOT2_BASE')

    # 配置参数文件路径定义
    ekf_config_path = PathJoinSubstitution(
        [FindPackageShare("linorobot2_base"), "config", "ekf.yaml"]
    )

    urdf_path = PathJoinSubstitution(
        [FindPackageShare("linorobot2_description"), "urdf/robots", f"{robot_base}.urdf.xacro"]
    )

    rviz_config_path = PathJoinSubstitution(
        [FindPackageShare('linorobot2_description'), 'rviz', 'description.rviz']
    )

    return LaunchDescription([
        DeclareLaunchArgument(
            name='robot_ns', 
            default_value='robot_0',
            description='Robot namespace'
        ),

        DeclareLaunchArgument(
            name='urdf', 
            default_value=urdf_path,
            description='URDF path'
        ),
        
        DeclareLaunchArgument(
            name='publish_joints', 
            default_value='true',
            description='Launch joint_states_publisher'
        ),

        DeclareLaunchArgument(
            name='rviz', 
            default_value='false',
            description='Run rviz'
        ),

        DeclareLaunchArgument(
            name='use_sim_time', 
            default_value='false',
            description='Use simulation time'
        ),

        DeclareLaunchArgument(
            name='odom_topic', 
            default_value='odom',
            description='EKF out odometry topic'
        ),

        DeclareLaunchArgument(
            name='target_frame', 
            default_value='odom',
            description='Fix frame for all robots'
        ),

        DeclareLaunchArgument(
            name='spawn_x', 
            default_value='0.0',
            description='Robot spawn position in X axis'
        ),

        DeclareLaunchArgument(
            name='spawn_y', 
            default_value='0.0',
            description='Robot spawn position in Y axis'
        ),

        DeclareLaunchArgument(
            name='spawn_z', 
            default_value='0.0',
            description='Robot spawn position in Z axis'
        ),
            
        DeclareLaunchArgument(
            name='spawn_yaw', 
            default_value='0.0',
            description='Robot spawn heading'
        ),

        GroupAction(
            actions=[
                # 添加命名空间
                PushRosNamespace(LaunchConfiguration("robot_ns")),

                # 在命名空间中的节点
                Node(
                    package='joint_state_publisher',
                    executable='joint_state_publisher',
                    name='joint_state_publisher',
                    condition=IfCondition(LaunchConfiguration("publish_joints")),
                    parameters=[
                        {'use_sim_time': LaunchConfiguration('use_sim_time')}
                    ]
                ),

                Node(
                    package='robot_state_publisher',
                    executable='robot_state_publisher',
                    name='robot_state_publisher',
                    output='screen',
                    parameters=[
                        {
                            'use_sim_time': LaunchConfiguration('use_sim_time'),
                            'robot_description': Command([
                                'xacro ', LaunchConfiguration('urdf'),
                                ' robot_ns:=', LaunchConfiguration('robot_ns')  # 传递 robot_ns 参数
                                ]),
                            'frame_prefix': [LaunchConfiguration('robot_ns'), TextSubstitution(text='/')]  # 动态拼接
                        }
                    ]
                ),
                
                Node(
                    package='gazebo_ros',
                    executable='spawn_entity.py',
                    name='urdf_spawner',
                    output='screen',
                    arguments=[
                        '-topic', 'robot_description', 
                        '-entity', [TextSubstitution(text='linorobot2_'), LaunchConfiguration('robot_ns')], 
                        '-x', LaunchConfiguration('spawn_x'),
                        '-y', LaunchConfiguration('spawn_y'),
                        '-z', LaunchConfiguration('spawn_z'),
                        '-Y', LaunchConfiguration('spawn_yaw'),
                    ]
                ),

                Node(
                    package='linorobot2_gazebo',
                    executable='command_timeout.py',
                    name='command_timeout'
                ),

                Node(
                    package='robot_localization',
                    executable='ekf_node',
                    name='ekf_filter_node',
                    output='screen',
                    parameters=[
                        {'use_sim_time': LaunchConfiguration('use_sim_time')}, 
                        ekf_config_path
                    ],
                    remappings=[("odometry/filtered", LaunchConfiguration("odom_topic"))]
                ),

                # Include odom_tf_publish.launch.py and pass parameters
                IncludeLaunchDescription(
                    PythonLaunchDescriptionSource(PathJoinSubstitution([FindPackageShare('odom_tf_publisher'), 'launch', 'tf_pub.launch.py'])),
                    launch_arguments={
                        'target_frame': LaunchConfiguration('target_frame'),
                        'robot_ns': LaunchConfiguration('robot_ns')
                    }.items()
                )
            ]
        )

    ])

#sources: 
#https://navigation.ros.org/setup_guides/index.html#
#https://answers.ros.org/question/374976/ros2-launch-gazebolaunchpy-from-my-own-launch-file/
#https://github.com/ros2/rclcpp/issues/940